package com.hyf.okhttp3demo.activity;

import android.Manifest;
import android.os.Bundle;
import android.os.Environment;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

import com.hyf.okhttp3demo.Config;
import com.hyf.okhttp3demo.R;
import com.hyf.okhttp3demo.support.DownLoadFileInterceptor;
import com.hyf.okhttp3demo.support.ProgressResponseBody;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import pub.devrel.easypermissions.AfterPermissionGranted;
import pub.devrel.easypermissions.EasyPermissions;

public class InterceptorActivity extends AppCompatActivity {
    private static final int RC_WRITE_SD_CARD = 144;
    private Button mButton;
    private TextView mTextView;

    private OkHttpClient mOkHttpClient;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_interceptor);
        mButton = (Button) findViewById(R.id.btn_start_download);
        mTextView = (TextView) findViewById(R.id.tv_result);
        mOkHttpClient = new OkHttpClient.Builder()
                .addNetworkInterceptor(new DownLoadFileInterceptor(new ProgressResponseBody.ProgressListener() {
                    @Override
                    public void update(long bytesRead, long contentLength, final boolean done) {
                        final int progress = (int) (bytesRead * 1.0 / contentLength * 100);
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                if (done) {
                                    mTextView.setText("下载完成！");
                                } else {
                                    mTextView.setText("已下载" + progress + "%");
                                }
                            }
                        });
                    }
                })).build();
        mButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                startDownLoad();
            }
        });

    }

    @AfterPermissionGranted(RC_WRITE_SD_CARD)
    private void startDownLoad() {
        String[] pers = {Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.WRITE_EXTERNAL_STORAGE};
        if (EasyPermissions.hasPermissions(this, pers)) {
            final Request request = new Request.Builder()
                    .url(Config.API.URL_GET_DOWNLOAD_FILE)
                    .build();
            mOkHttpClient.newCall(request).enqueue(new Callback() {
                @Override
                public void onFailure(Call call, IOException e) {
                    updateUi(e.getLocalizedMessage());
                }

                @Override
                public void onResponse(Call call, Response response) throws IOException {
                    InputStream is = response.body().byteStream();
                    String url = call.request().url().toString();
                    url = url.substring(url.lastIndexOf("/"));
                    File file = new File(Environment.getExternalStorageDirectory().getAbsolutePath(), url);
                    FileOutputStream fos = new FileOutputStream(file);
                    int len = 0;
                    byte[] bytes = new byte[2048];
                    while ((len = is.read(bytes)) != -1) {
                        fos.write(bytes, 0, len);
                    }
                    fos.flush();
                    is.close();
                    fos.close();
                }
            });
        } else {
            EasyPermissions.requestPermissions(this, "申请获取读写权限", RC_WRITE_SD_CARD, pers);
        }
    }


    private void updateUi(final String msg) {
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                mTextView.setText(msg);
            }
        });
    }
}
